<?php


namespace app\admin\controller\admin;


use app\admin\annotation\UseAuth;
use app\admin\controller\BaseController;
use app\admin\validate\AdminDepartmentValidate;
use app\common\http\exception\AppException;
use app\common\library\FormDataValidate;
use app\common\model\AdminDepartment;
use think\Db;
use think\Exception;
use think\facade\Hook;
use think\Response;
use think\response\Json;

/**
 * Class DepartmentController
 * @package app\admin\controller\admin
 * @UseAuth(policy="Acl")
 */
class DepartmentController extends BaseController
{
    /**
     * 部门列表
     * @return mixed
     * @route('admin/super/departments', 'get')
     */
    public function index()
    {
        $result = AdminDepartment::select();

        return $this->success([
            'items'=>$result,
        ]);
    }


    /**
     * 添加 / 编辑组织
     * @param string $action
     * @return Response|Json
     * @throws AppException
     * @route('admin/super/department/:action', 'post')
     */
    public function post($action)
    {
        $form = new FormDataValidate(AdminDepartmentValidate::class, $action);

        if ($form->id) {
            $data = AdminDepartment::where('id', $form->id)->find();
            if (!$data) {
                throw new AppException('记录不存在');
            }
        } else {
            $data = new AdminDepartment();
        }
        $data->save($form->toArray());

        $this->recordActionLog(sprintf('%s组织：%s', $action == 'add' ? '添加' : '编辑', $data->name));

        return $this->success($data);
    }


    /**
     * 组织删除
     * @param $key
     * @return Response|Json
     * @throws AppException
     * @route('admin/super/department/:key', 'delete')
     */
    public function delete($key)
    {
        $id = explode(',', $key);
        $list = AdminDepartment::where('id', 'in', $id)->field('id,name')->select();
        Db::startTrans();
        try {
            foreach ($list as $item) {
                $this->recordActionLog(sprintf('删除组织：%s', $item->name));
                $item->delete();
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();

            throw new AppException($e->getMessage());
        }

        return $this->success();
    }

}
